package com.sunop.panticlass.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.sunop.api.client.user.UserClient;
import com.sunop.panticlass.mapper.ClassNoiceMapper;
import com.sunop.panticlass.model.ClassPO;
import com.sunop.panticlass.service.ClassService;
import com.sunop.panticommon.config.RabbitConfig;
import com.sunop.panticommon.entity.Result;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID;


@Service
@RequiredArgsConstructor
public class ClassServiceImpl implements ClassService {

    private final RabbitAdmin rabbitAdmin;
    private final RabbitConfig rabbitConfig;
    private final RabbitTemplate rabbitTemplate;
    private final UserClient userClient;
    private final ClassNoiceMapper classNoiceMapper;


    /**
     * 创建班级消息队列
     */
    public void createClassQueue(String classId) {
        rabbitAdmin.declareExchange(rabbitConfig.createClassExchange(classId));
        rabbitAdmin.declareQueue(rabbitConfig.createClassQueue(classId));
        rabbitAdmin.declareBinding(rabbitConfig.bindClassQueueToExchange(classId));
    }

    /**
     * 删除班级队列
     */
    public void removeClassQueue(String classId) {
        rabbitAdmin.deleteQueue("class.queue." + classId);
        rabbitAdmin.deleteExchange("class.exchange." + classId);
    }

    @Override
    public Result getMessage() {
        ClassPO classPO = null;
        try {
            int classId = userClient.getclassId(StpUtil.getLoginIdAsInt());
            classPO = classNoiceMapper.getMessage(classId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if(classPO == null)return Result.error("未找到班级消息");
        return Result.success(classPO);
    }

    @Override
    public Result commitTask(int massageId) {
        List<Integer> problemIds = classNoiceMapper.getOverProblemIds(massageId);//作业ids
        List<Integer> overIds = userClient.getUserOverProblemIds(StpUtil.getLoginIdAsInt());//已做ids
        //如果overIds包含了problemIds，则返回正确
        if (overIds.containsAll(problemIds)) {
            return Result.success(null,"提交成功");
        }else{
            return Result.error("未完成作业");
        }

    }

    /**
     * 检查队列是否存在
     */
    public boolean existsClassQueue(String classId) {
        rabbitAdmin.getQueueProperties("class.queue." + classId);
        return true;
    }

    /**
     * 发送班级消息（自动创建队列）
     */
    public void sendClassMessage(ClassPO classPO, List<Integer> problemIds) {
        if (!existsClassQueue(String.valueOf(classPO.getClassId()))) {
            createClassQueue(String.valueOf(classPO.getClassId()));
        }
        int id= Math.abs(UUID.randomUUID().hashCode());
        classPO.setId(id);
        rabbitTemplate.convertAndSend(
                "class.exchange." + classPO.getClassId(),
                "",
                classPO
        );
        classNoiceMapper.saveProblemIds(classPO.getClassId(), id,problemIds);
    }
//    /**
//     * 为学生订阅班级消息
//     * @param studentId 学生ID
//     * @param classId 班级ID
//     */
//    public void subscribeToClass(int studentId, String classId) {
//        String queueName = "class.queue." + classId;
//
//        // 确保队列存在
//        if (rabbitAdmin.getQueueProperties(queueName) == null) {
//            rabbitAdmin.declareExchange(rabbitConfig.createClassExchange(classId));
//            rabbitAdmin.declareQueue(rabbitConfig.createClassQueue(classId));
//            rabbitAdmin.declareBinding(rabbitConfig.bindClassQueueToExchange(classId));
//        }

//        // 保存订阅关系到MySQL
//        if (!existsByStudentIdAndClassId(studentId, classId)) {
//            StudentClassSubscription subscription = new StudentClassSubscription();
//            subscription.setStudentId(studentId);
//            subscription.setClassId(classId);
//            subscriptionRepository.save(subscription);
//        }
//    }
}
